<template>
  <!-- 管理员布局 -->
  <el-container v-if="isAdmin" class="admin-layout">
    <!-- 左侧边栏 -->
    <ManageSider />

    <!-- 右侧内容区 -->
    <el-container direction="vertical">
      <!-- 顶部导航栏 -->
      <ManageHeader />

      <!-- 主内容区 -->
      <el-main class="admin-main-content">
        <div class="admin-container">
<!--          <div class="action-bar">-->
<!--            <h1>社区管理</h1>-->
<!--            <el-button-->
<!--                type="danger"-->
<!--                @click="handleBatchDelete"-->
<!--                icon="el-icon-delete"-->
<!--                :disabled="selectedPosts.length === 0"-->
<!--            >-->
<!--              批量删除-->
<!--            </el-button>-->
<!--          </div>-->

          <el-table
              :data="paginatedPosts"
              style="width: 100%"
              stripe
              @selection-change="handleSelectionChange"
          >
<!--            <el-table-column type="selection" width="55"></el-table-column>-->
            <el-table-column prop="id" label="帖子ID" width="120"></el-table-column>
            <el-table-column prop="userName" label="发布者" width="150"></el-table-column>
            <el-table-column prop="title" label="标题" width="200"></el-table-column>
            <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
            <el-table-column prop="date" label="发布时间" width="180">
              <template #default="{row}">
                {{ formatDate(row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="likes" label="点赞数" width="100" align="center"></el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                    type="text"
                    @click="viewPostDetail(scope.row)"
                    icon="el-icon-view"
                >
                  详情
                </el-button>
                <el-button
                    type="text"
                    @click="deletePost(scope.row.id)"
                    icon="el-icon-delete"
                    style="color: #f56c6c"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="totalPosts"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
              style="margin-top: 20px;"
          />
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 普通用户布局 -->
  <div v-else>
    <NormalHeader />
    <div class="permission-denied">
      <h1>管理员功能暂时不对您开放</h1>
    </div>
  </div>

  <!-- 帖子详情弹框 -->
  <el-dialog v-model="dialogVisible" title="帖子详情" width="60%">
    <div v-if="postDetail" class="post-detail">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="帖子ID">{{ postDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="发布者">{{ postDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ postDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDate(postDetail.date) }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ postDetail.likes }}</el-descriptions-item>
      </el-descriptions>

      <div class="post-content">
        <h3 style="margin: 20px 0 10px;">内容详情</h3>
        <div class="content-text">{{ postDetail.content }}</div>
      </div>

      <div class="post-image" v-if="postDetail.image">
        <h3 style="margin: 20px 0 10px;">图片预览</h3>
        <el-image
            :src="getImageUrl(postDetail.image)"
            :preview-src-list="[getImageUrl(postDetail.image)]"
            fit="cover"
            style="width: 300px; height: 300px; border-radius: 4px;"
        ></el-image>
      </div>
      <!-- 评论列表部分 -->
      <div class="comment-section" v-if="postDetail.commentList && postDetail.commentList.length">
        <h3 style="margin: 20px 0 10px;">评论列表</h3>
        <el-table :data="postDetail.commentList" border>
          <el-table-column prop="id" label="评论ID" width="100"></el-table-column>
          <el-table-column prop="userName" label="评论者" width="150"></el-table-column>
          <el-table-column prop="content" label="评论内容"></el-table-column>
          <el-table-column prop="date" label="评论时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.date) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{row}">
              {{ row.status === 0 ? '正常' : '已删除' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                  type="text"
                  @click="deleteComment(scope.row.id)"
                  style="color: #f56c6c"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import {GetPosts, DeletePost, GetPost, deleteComment} from "@/api";
import dayjs from 'dayjs';
import NormalHeader from "@/components/NormalHeader.vue";
import ManageSider from "@/components/ManageSider.vue";
import ManageHeader from "@/components/ManageHeader.vue";

export default {
  name: "ManageCommunity",
  components: {
    NormalHeader,
    ManageSider,
    ManageHeader
  },
  data() {
    return {
      isAdmin: false,
      posts: [],
      pageSize: 8,
      currentPage: 1,
      totalPosts: 0,
      selectedPosts: [],
      dialogVisible: false,
      postDetail: null
    };
  },
  computed: {
    paginatedPosts() {
      if (!Array.isArray(this.posts)) return [];
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.posts.slice(start, end);
    }
  },
  async mounted() {
    await this.checkAdminPermission();
    if (this.isAdmin) {
      await this.fetchPosts();
    }
  },
  methods: {
    // 新增删除评论方法
    async deleteComment(commentId) {
      try {
        await ElMessageBox.confirm(
            '确定要删除该评论吗?',
            '提示',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );

        const { data } = await deleteComment(commentId);

        if (data.code === 200) {
          ElMessage.success("评论删除成功");
          // 重新加载帖子详情以更新评论列表
          await this.viewPostDetail({ id: this.postDetail.id });
        } else {
          ElMessage.error(data.message || "评论删除失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("评论删除失败");
        }
      }
    },
    async checkAdminPermission() {
      const userType = localStorage.getItem("type");
      this.isAdmin = userType === "0";
    },
    async fetchPosts() {
      try {
        const { data } = await GetPosts();
        if (data.code === 200) {
          this.posts = Array.isArray(data.data) ? data.data : [];
          this.totalPosts = this.posts.length;
        } else {
          ElMessage.error(data.message || "获取帖子列表失败");
        }
      } catch (error) {
        ElMessage.error("获取帖子列表失败");
        console.error(error);
      }
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    },
    getImageUrl(imageName) {
      if (!imageName) return '';
      return require(`@/assets/uploads/${imageName}`);
    },
    async viewPostDetail(post) {
      try {
        const { data } = await GetPost(post.id);
        if (data.code === 200) {
          this.postDetail = data.data;
          this.dialogVisible = true;
        } else {
          ElMessage.error(data.message || "获取帖子详情失败");
        }
      } catch (error) {
        ElMessage.error("获取帖子详情失败");
        console.error(error);
      }
    },
    handleSelectionChange(selection) {
      this.selectedPosts = selection;
    },
    async deletePost(postId) {
      try {
        await ElMessageBox.confirm(
            '确定要删除该帖子吗?',
            '提示',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );

        const { data } = await DeletePost(postId);

        if (data.code === 200) {
          ElMessage.success("删除成功");
          await this.fetchPosts();
        } else {
          ElMessage.error(data.message || "删除失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("删除失败");
        }
      }
    },
    // async handleBatchDelete() {
    //   if (this.selectedPosts.length === 0) {
    //     ElMessage.warning("请至少选择一条帖子");
    //     return;
    //   }
    //
    //   try {
    //     await ElMessageBox.confirm(
    //         `确定要删除选中的 ${this.selectedPosts.length} 条帖子吗?`,
    //         '提示',
    //         { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    //     );
    //
    //     const ids = this.selectedPosts.map(post => post.id).join(',');
    //     const { data } = await DeletePosts(ids);
    //
    //     if (data.code === 200) {
    //       ElMessage.success("批量删除成功");
    //       await this.fetchPosts();
    //       this.selectedPosts = [];
    //     } else {
    //       ElMessage.error(data.message || "批量删除失败");
    //     }
    //   } catch (error) {
    //     if (error !== 'cancel') {
    //       ElMessage.error("批量删除失败");
    //     }
    //   }
    // },
    handlePageChange(page) {
      this.currentPage = page;
    }
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100vh;
}

/* 评论部分样式 */
.comment-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
.admin-main-content {
  padding: 20px;
  height: 100vh;
  overflow-y: auto;
  margin-left: 200px; /* 等于侧边栏宽度 */
  background-color: #f5f7fa;
}

.admin-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.permission-denied {
  text-align: center;
  padding: 100px 0;
}

.post-detail {
  line-height: 1.6;
}

.post-content {
  margin-top: 20px;
}

.content-text {
  white-space: pre-line;
  line-height: 1.8;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .admin-container {
    padding: 15px;
  }

  .admin-main-content {
    margin-left: 0;
  }
}
</style>
